var express = require('express');
var router = express.Router();
// 引入数据库查询
let query = require("../db/db").query
    // 引入上传图片插件
const multer = require("multer")
    // 定义上传图片存储的文件夹
const upload = multer({ dest: __dirname + "/../../uploads" })
    /* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

// 登录时候post方法 /login
// 响应前台的请求
router.post("/login", function(req, res, next) {
    // req.body获取前台传过来的数据
    // console.log(req.body)
    let { username, password } = req.body
        // 将传过来的数据与数据库对比并得出结果
    let sql = "select * from myshop.user where username=? and password=?";
    let values = [username, password];
    query(sql, values, function(err, results) {
        if (results.length === 0) {
            res.json({
                code: -1,
                meg: "账号密码不正确",
                data: []
            })
        } else {
            // 将user_id加载到session上
            req.session.user_id = results[0].user_id
            res.json({
                code: 1,
                meg: "登录成功",
                data: []
            })
        }
    })

    /*     // 给前台返回数据
    res.json({
        code: 1,
        username,
        password,
        data: []
    }) */

    // 上传图片的接口
    router.post("/uploadImg", upload.single("file"), function(req, res, next) {
        const file = req.file;
        file.url = `${file.filename}`;
        res.send(file);
    });
})

module.exports = router;